package com.soxing.braindata.service.docker;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Volume;
import com.soxing.braindata.domain.vo.EegVo;
import com.soxing.common.utils.response.WebResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import us.hebi.matlab.mat.format.Mat5;
import us.hebi.matlab.mat.format.Mat5File;
import us.hebi.matlab.mat.types.Cell;
import us.hebi.matlab.mat.types.Char;
import us.hebi.matlab.mat.types.Matrix;


import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;


@Service
public class EEGViewServiceeeeeImpl implements IEEGViewService{

    @Resource
    DockerClient dockerClient;


    @Value("${docker.mapping}")
    String mapping;


    @Value("#{new Boolean('${docker.needMapping}')}")
    boolean needMapping;



    @Override
    public WebResponse view(String path, int star, int end) {


        //docker run -it -v /home/webrain/Desktop/repo:/export liuda111/tomat:v3 /root/matlab_script/ToMat /export/sub_12779-2s /export/666.mat
        //docker run -v /home/webrain/Desktop/share/file:/export liuda111/tomat:v5 /root/matlab_script/ToMat /export/sub01_open_prepro_prepro.zip /export/666.mat
         int index = path.lastIndexOf("/");
         String fPath = path.substring(0,index);//这种sub都是包含都不包含尾巴的
         String name = path.substring(index+1);



        String[] cmd = {"/root/matlab_script/ToMat","/export/"+name,"/export/result.mat"};
        CreateContainerResponse container = dockerClient.createContainerCmd("liuda111/tomat:v5")
                //.withName("ToMat"+name)
                .withCmd(cmd)
                .withBinds(Bind.parse(fPath+":/export")).exec();
        dockerClient.startContainerCmd(container.getId()).exec();


        //\home\webrain\Desktop\share\file\result.mat
        String matPath = fPath+"/"+"result.mat";



        //下面这个判断是在windows中开发的话
        if(needMapping){
            int index1 = matPath.indexOf("share");
            matPath = mapping+matPath.substring(index1+6);
            matPath = matPath.replace('/','\\');
            System.out.println();
        }




        File matFile = new File(matPath);
        int times = 0;
        try {
            while (!matFile.exists()) {
                Thread.sleep(1000);
                times++;
                if(times>10){
                    //todo 后续加个日志
                    return WebResponse.fail("mat文件读取超时");

                }
            }
        }catch (InterruptedException interruptedException){
            return WebResponse.fail(interruptedException);
        }



        EegVo eegVo = new EegVo();

        try{


            //todo 这里要切换一下路径 docker是在linux中运行的，读取现在是在windows中的开发环境汇总运行的
            Mat5File file = Mat5.readFromFile(matFile);
            //Struct eeg = file.getStruct("EEG");
            Matrix srate = file.getMatrix("srate");
            double[] srated = new double[1];
            Double aDouble1 = Double.valueOf(srate.toString());
            srated[0] = aDouble1;
            eegVo.setSrate(srated);

            Matrix data = file.getMatrix("data");
            List<List<Double>> data1 = new ArrayList<>();
            for (int i = 0; i < data.getNumRows(); i++) {
                List<Double> list = new ArrayList<>();
                for (int j = (int) (star * aDouble1); j < end * aDouble1; j++) {
                    if (j == data.getNumCols()) {
                        break;
                    } else {
                        list.add(data.getDouble(i, j));
                    }
                }
                data1.add(list);
            }
            eegVo.setData(data1);







            Char ref = file.getChar("ref");
            eegVo.setRef(String.valueOf(ref));

            Cell event_type = file.getCell("event_type");
            List<String> list2 = new ArrayList<>();
            for (int i = 0; i < event_type.getNumCols(); i++) {
                list2.add(String.valueOf(event_type.get(i)));
            }
            eegVo.setEvent_type(list2);

            Matrix m1  = file.getMatrix("event_latency");
            List<Double> list1 = new ArrayList<>();
            for (int i = 0; i < m1.getNumCols(); i++) {
                double aDouble = m1.getDouble(i);
                list1.add(aDouble);
            }
            double[] doubles = new double[list1.size()];
            for (int i = 0; i < list1.size(); i++) {
                doubles[i] = list1.get(i);
            }
            eegVo.setEvent_latency(doubles);

            Char labels = file.getChar("labels");
            List<String> list3 = new ArrayList<>();
//            for (int i = 0; i < labels.getNumCols(); i++) {
//                list3.add(String.valueOf(labels.getChar(i)));
//            }
            //因为label不是单个字符，而是字符串，所以做了一下修改
            for (int i = 0; i < labels.getNumRows(); i++) {
                list3.add(String.valueOf(labels.getRow(i)));
            }
            eegVo.setLabels(list3);

            Matrix m4 = file.getMatrix("theta");
            List<Double> list4 = new ArrayList<>();
            for (int i = 0; i < m4.getNumCols(); i++) {
                double aDouble = m4.getDouble(i);
                list4.add(aDouble);
            }
            double[] doubles4 = new double[list4.size()];
            for (int i = 0; i < list4.size(); i++) {
                doubles4[i] = list4.get(i);
            }
            eegVo.setTheta(doubles4);

            Matrix m5 = file.getMatrix("radius");
            List<Double> list5 = new ArrayList<>();
            for (int i = 0; i < m5.getNumCols(); i++) {
                double aDouble = m5.getDouble(i);
                list5.add(aDouble);
            }
            double[] doubles5 = new double[list5.size()];
            for (int i = 0; i < list5.size(); i++) {
                doubles5[i] = list5.get(i);
            }
            eegVo.setRadius(doubles5);

            Matrix xmin = file.getMatrix("xmin");
            double[] xmind = new double[1];
            xmind[0] = Double.valueOf(xmin.toString());
            eegVo.setXmin(xmind);

            Matrix xmax = file.getMatrix("xmax");
            double[] xmaxd = new double[1];
            xmaxd[0] = Double.valueOf(xmax.toString());
            eegVo.setXmax(xmaxd);

            eegVo.setStart(star);
            eegVo.setEnd(end);

            data = file.getMatrix("erp");
            data1 = new ArrayList<>();
            for (int i = 0; i < data.getNumRows(); i++) {
                List<Double> list = new ArrayList<>();
                for (int j = 0; j < (xmaxd[0] - xmind[0]) * aDouble1; j++) {
                    if (j == data.getNumCols()) {
                        break;
                    } else {
                        list.add(data.getDouble(i, j));
                    }
                }
                data1.add(list);
            }
            eegVo.setErp(data1);




        }catch (Exception e) {
            e.printStackTrace();

        }
        return WebResponse.success(eegVo);
    }




    public void exec(String path)
    {

        String v  = "/export";

        Volume configVol = new Volume(path);
        String[] cmd = {"/root/matlab_script/wb_pipeline_EEG_QA_v2","/export/sub01_open_prepro_prepro.zip","/export/2-QA","1","1","1","all","0.4","5","50","3","0","0.6","[]","0.3","50","[]"};
        CreateContainerResponse container = dockerClient.createContainerCmd("liuda111/eeg-tools:v7").withName("test04")
                .withCmd(cmd)
                .withBinds(Bind.parse("/home/webrain/Desktop/share/file:/export")).exec();


        System.out.println("success_______________");
        dockerClient.startContainerCmd(container.getId()).exec();
        System.out.println(container);



    }
}
